<template>
  <div class="admin-groups-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">小组管理</h1>
      <p class="page-subtitle">管理学习小组、成员和活动</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索小组名称或描述"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="searchGroups"
        />
        <el-select v-model="groupStatus" placeholder="小组状态" class="status-select">
          <el-option label="全部" value="" />
          <el-option label="正常" value="active" />
          <el-option label="审核中" value="pending" />
          <el-option label="已禁用" value="disabled" />
        </el-select>
        <el-select v-model="groupCategory" placeholder="小组分类" class="category-select">
          <el-option label="全部" value="" />
          <el-option label="行测" value="行测" />
          <el-option label="申论" value="申论" />
          <el-option label="面试" value="面试" />
          <el-option label="公基" value="公基" />
          <el-option label="其他" value="其他" />
        </el-select>
      </div>
      <div class="toolbar-actions">
        <el-button type="primary" @click="createGroup">创建小组</el-button>
        <el-button type="default" @click="batchActions">批量操作</el-button>
        <el-button type="default" @click="exportGroupList">导出列表</el-button>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalGroups }}</span>
          <span class="stat-label">小组总数</span>
        </div>
        <el-icon class="stat-icon"><UserFilled /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ activeGroups }}</span>
          <span class="stat-label">活跃小组</span>
        </div>
        <el-icon class="stat-icon"><StarFilled /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ pendingGroups }}</span>
          <span class="stat-label">审核中</span>
        </div>
        <el-icon class="stat-icon"><Hourglass /></el-icon>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <span class="stat-number">{{ totalMembers }}</span>
          <span class="stat-label">总成员数</span>
        </div>
        <el-icon class="stat-icon"><Users /></el-icon>
      </el-card>
    </div>

    <!-- 小组表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="isLoading"
        :data="groupsData"
        style="width: 100%"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="groupId" label="小组ID" width="120" />
        <el-table-column label="小组名称" min-width="200">
          <template #default="scope">
            <div class="group-info">
              <el-avatar :src="scope.row.avatar" class="group-avatar">
                <span v-if="!scope.row.avatar">{{ scope.row.name.charAt(0) }}</span>
              </el-avatar>
              <span class="group-name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="100" />
        <el-table-column prop="description" label="描述" min-width="250">
          <template #default="scope">
            <div class="group-description" v-html="truncateContent(scope.row.description)"></div>
          </template>
        </el-table-column>
        <el-table-column prop="members" label="成员数" width="100">
          <template #default="scope">
            <span class="member-count">{{ scope.row.members }}人</span>
          </template>
        </el-table-column>
        <el-table-column prop="activityCount" label="活动数" width="100" />
        <el-table-column prop="createTime" label="创建时间" min-width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :class="getStatusClass(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewGroupDetail(scope.row)">查看</el-button>
            <el-button type="default" size="small" @click="editGroup(scope.row)">编辑</el-button>
            <el-button 
              type="default" 
              size="small" 
              :class="scope.row.status === 'active' ? 'text-danger' : 'text-success'"
              @click="toggleGroupStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 小组详情模态框 -->
    <el-dialog v-model="showGroupDetailModal" :title="`小组详情 - ${selectedGroup?.name}`" width="900px" append-to-body>
      <div v-if="selectedGroup" class="group-detail">
        <div class="detail-header">
          <el-avatar :src="selectedGroup.avatar" class="group-avatar-large">
            <span v-if="!selectedGroup.avatar">{{ selectedGroup.name.charAt(0) }}</span>
          </el-avatar>
          <div class="group-header-info">
            <h3 class="detail-title">
              {{ selectedGroup.name }}
              <el-tag :class="getStatusClass(selectedGroup.status)">{{ getStatusLabel(selectedGroup.status) }}</el-tag>
            </h3>
            <div class="group-meta">
              <span class="meta-item">{{ selectedGroup.category }}</span>
              <span class="meta-item">{{ selectedGroup.members }} 成员</span>
              <span class="meta-item">{{ selectedGroup.activityCount }} 活动</span>
              <span class="meta-item">创建于 {{ selectedGroup.createTime }}</span>
            </div>
          </div>
        </div>

        <div class="detail-tabs">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="小组信息">
              <div class="tab-content">
                <div class="info-section">
                  <h4 class="section-title">小组描述</h4>
                  <div class="description-content" v-html="selectedGroup.description"></div>
                </div>
                <div class="info-section">
                  <h4 class="section-title">创建者信息</h4>
                  <div class="creator-info">
                    <el-avatar :src="selectedGroup.creator.avatar" class="creator-avatar">
                      <span v-if="!selectedGroup.creator.avatar">{{ selectedGroup.creator.nickname.charAt(0) }}</span>
                    </el-avatar>
                    <div class="creator-details">
                      <p class="creator-name">{{ selectedGroup.creator.nickname }}</p>
                      <p class="creator-role">{{ selectedGroup.creator.role }}</p>
                      <p class="creator-join-date">加入时间：{{ selectedGroup.creator.joinTime }}</p>
                    </div>
                  </div>
                </div>
                <div class="info-section">
                  <h4 class="section-title">小组设置</h4>
                  <div class="settings-list">
                    <div class="setting-item">
                      <span class="setting-label">是否公开：</span>
                      <span class="setting-value">{{ selectedGroup.isPublic ? '是' : '否' }}</span>
                    </div>
                    <div class="setting-item">
                      <span class="setting-label">加入方式：</span>
                      <span class="setting-value">{{ selectedGroup.joinMethod === 'open' ? '开放加入' : selectedGroup.joinMethod === 'approval' ? '审核加入' : '邀请加入' }}</span>
                    </div>
                    <div class="setting-item">
                      <span class="setting-label">成员上限：</span>
                      <span class="setting-value">{{ selectedGroup.memberLimit === 0 ? '无限制' : selectedGroup.memberLimit }}人</span>
                    </div>
                    <div class="setting-item">
                      <span class="setting-label">发帖权限：</span>
                      <span class="setting-value">{{ selectedGroup.postPermission === 'all' ? '所有成员' : '管理员' }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="成员列表">
              <div class="tab-content">
                <div class="members-table-section">
                  <el-table
                    :data="selectedGroup.membersList"
                    style="width: 100%"
                    border
                    size="small"
                  >
                    <el-table-column prop="userId" label="用户ID" width="120" />
                    <el-table-column label="用户信息" min-width="200">
                      <template #default="scope">
                        <div class="member-info">
                          <el-avatar :src="scope.row.avatar" class="member-avatar">
                            <span v-if="!scope.row.avatar">{{ scope.row.nickname.charAt(0) }}</span>
                          </el-avatar>
                          <div class="member-details">
                            <p class="member-name">{{ scope.row.nickname }}</p>
                            <p class="member-role">{{ scope.row.role === 'owner' ? '创建者' : scope.row.role === 'admin' ? '管理员' : '成员' }}</p>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="joinTime" label="加入时间" min-width="150" />
                    <el-table-column prop="lastActive" label="最后活跃" min-width="150" />
                    <el-table-column prop="contributions" label="贡献值" width="100" />
                    <el-table-column label="操作" width="150" fixed="right">
                      <template #default="scope">
                        <el-button type="text" size="small" @click="changeMemberRole(scope.row)">修改角色</el-button>
                        <el-button 
                          v-if="scope.row.role !== 'owner'"
                          type="text" 
                          size="small" 
                          class="text-danger"
                          @click="removeMember(scope.row)"
                        >
                          移除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="活动记录">
              <div class="tab-content">
                <div class="activities-table-section">
                  <el-table
                    :data="selectedGroup.activities"
                    style="width: 100%"
                    border
                    size="small"
                  >
                    <el-table-column prop="activityId" label="活动ID" width="120" />
                    <el-table-column prop="title" label="活动标题" min-width="250" />
                    <el-table-column prop="type" label="活动类型" width="120">
                      <template #default="scope">
                        <el-tag>{{ scope.row.type }}</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="creator" label="创建者" width="120" />
                    <el-table-column prop="participants" label="参与人数" width="100" />
                    <el-table-column prop="createTime" label="创建时间" min-width="150" />
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="scope">
                        <el-tag :class="getActivityStatusClass(scope.row.status)">{{ scope.row.status }}</el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <div class="detail-actions">
          <el-button 
            type="primary" 
            @click="toggleGroupStatus(selectedGroup)"
          >
            {{ selectedGroup.status === 'active' ? '禁用小组' : '启用小组' }}
          </el-button>
          <el-button type="primary" @click="editGroup(selectedGroup)">编辑小组</el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="showGroupDetailModal = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 创建/编辑小组模态框 -->
    <el-dialog v-model="showCreateEditModal" :title="editingGroup ? '编辑小组' : '创建小组'" width="700px" append-to-body>
      <el-form ref="groupForm" :model="groupForm" label-width="100px" :rules="groupRules">
        <el-form-item label="小组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入小组名称" />
        </el-form-item>
        <el-form-item label="小组分类" prop="category">
          <el-select v-model="groupForm.category" placeholder="请选择小组分类">
            <el-option label="行测" value="行测" />
            <el-option label="申论" value="申论" />
            <el-option label="面试" value="面试" />
            <el-option label="公基" value="公基" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="小组描述" prop="description">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            rows="4"
            placeholder="请输入小组描述"
          />
        </el-form-item>
        <el-form-item label="小组头像">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="groupForm.avatar" :src="groupForm.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch v-model="groupForm.isPublic" />
        </el-form-item>
        <el-form-item label="加入方式" prop="joinMethod">
          <el-radio-group v-model="groupForm.joinMethod">
            <el-radio label="open">开放加入</el-radio>
            <el-radio label="approval">审核加入</el-radio>
            <el-radio label="invite">邀请加入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成员上限" prop="memberLimit">
          <el-input-number v-model="groupForm.memberLimit" :min="0" :max="1000" placeholder="0表示无限制" />
        </el-form-item>
        <el-form-item label="发帖权限" prop="postPermission">
          <el-radio-group v-model="groupForm.postPermission">
            <el-radio label="all">所有成员</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeCreateEditModal">取消</el-button>
        <el-button type="primary" @click="saveGroup">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量操作下拉菜单 -->
    <el-dropdown ref="batchActionsDropdown" trigger="click" @command="handleBatchCommand">
      <span class="el-dropdown-link">
        批量操作 <el-icon class="el-icon-arrow-down"></el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="batchEnable" :disabled="!hasSelection">批量启用</el-dropdown-item>
          <el-dropdown-item command="batchDisable" :disabled="!hasSelection">批量禁用</el-dropdown-item>
          <el-dropdown-item command="batchDelete" :disabled="!hasSelection" divided>批量删除</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 搜索和筛选条件
const searchKeyword = ref('');
const groupStatus = ref('');
const groupCategory = ref('');

// 加载状态
const isLoading = ref(false);

// 模态框控制
const showGroupDetailModal = ref(false);
const showCreateEditModal = ref(false);

// 编辑状态
const editingGroup = ref(false);

// 选择的小组
const selectedGroup = ref<any>(null);

// 选中的行
const selectedRows = ref<any[]>([]);

// 统计数据
const totalGroups = ref(326);
const activeGroups = ref(289);
const pendingGroups = ref(12);
const totalMembers = ref(15824);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 326
});

// 详情页标签
const activeTab = ref('0');

// 小组表单数据
const groupForm = reactive({
  groupId: '',
  name: '',
  category: '行测',
  description: '',
  avatar: '',
  isPublic: true,
  joinMethod: 'open', // 'open', 'approval', 'invite'
  memberLimit: 0,
  postPermission: 'all' // 'all', 'admin'
});

// 表单验证规则
const groupRules = {
  name: [{ required: true, message: '请输入小组名称', trigger: 'blur' }, { min: 2, max: 20, message: '小组名称长度在 2 到 20 个字符之间', trigger: 'blur' }],
  category: [{ required: true, message: '请选择小组分类', trigger: 'change' }],
  description: [{ required: true, message: '请输入小组描述', trigger: 'blur' }, { min: 10, max: 500, message: '小组描述长度在 10 到 500 个字符之间', trigger: 'blur' }]
};

// 模拟小组数据
const groupsData = ref<any[]>([
  {
    groupId: 'G001',
    name: '2024国考行测冲刺班',
    category: '行测',
    description: '专注于2024年国考行测科目的冲刺备考，分享解题技巧和复习资料。欢迎各位考生加入交流！',
    avatar: 'https://picsum.photos/id/1001/200/200',
    members: 356,
    activityCount: 28,
    status: 'active',
    createTime: '2024-04-10 09:30:00',
    isPublic: true,
    joinMethod: 'open',
    memberLimit: 500,
    postPermission: 'all',
    creator: {
      nickname: '行测大神',
      role: '管理员',
      joinTime: '2024-04-10 09:30:00'
    },
    membersList: [
      { userId: 'U001', nickname: '行测大神', role: 'owner', joinTime: '2024-04-10 09:30:00', lastActive: '刚刚', contributions: 350 },
      { userId: 'U002', nickname: '数资小王子', role: 'admin', joinTime: '2024-04-11 14:20:00', lastActive: '1小时前', contributions: 280 },
      { userId: 'U003', nickname: '判断推理专家', role: 'admin', joinTime: '2024-04-12 10:15:00', lastActive: '3小时前', contributions: 245 },
      { userId: 'U004', nickname: '公考小白', role: 'member', joinTime: '2024-04-13 16:40:00', lastActive: '昨天', contributions: 56 },
      { userId: 'U005', nickname: '努力备考中', role: 'member', joinTime: '2024-04-14 09:25:00', lastActive: '3天前', contributions: 42 }
    ],
    activities: [
      { activityId: 'A001', title: '行测模拟考试', type: '考试', creator: '行测大神', participants: 125, createTime: '2024-05-08 09:00:00', status: '已完成' },
      { activityId: 'A002', title: '资料分析专项训练', type: '练习', creator: '数资小王子', participants: 89, createTime: '2024-05-06 14:30:00', status: '已完成' },
      { activityId: 'A003', title: '判断推理技巧分享会', type: '分享', creator: '判断推理专家', participants: 156, createTime: '2024-05-04 19:00:00', status: '已完成' },
      { activityId: 'A004', title: '言语理解专项突破', type: '练习', creator: '行测大神', participants: 0, createTime: '2024-05-12 14:30:00', status: '即将开始' }
    ]
  },
  {
    groupId: 'G002',
    name: '申论高分训练营',
    category: '申论',
    description: '申论写作技巧分享，真题解析，高分经验交流。帮助你在申论考试中取得优异成绩！',
    avatar: 'https://picsum.photos/id/1002/200/200',
    members: 289,
    activityCount: 22,
    status: 'active',
    createTime: '2024-04-08 14:20:00',
    isPublic: true,
    joinMethod: 'open',
    memberLimit: 300,
    postPermission: 'all',
    creator: {
      nickname: '申论小王子',
      role: '管理员',
      joinTime: '2024-04-08 14:20:00'
    },
    membersList: [],
    activities: []
  },
  {
    groupId: 'G003',
    name: '面试技巧实战班',
    category: '面试',
    description: '公务员面试技巧分享，模拟面试训练，帮助你在面试环节脱颖而出。',
    avatar: 'https://picsum.photos/id/1003/200/200',
    members: 245,
    activityCount: 18,
    status: 'active',
    createTime: '2024-04-05 10:15:00',
    isPublic: true,
    joinMethod: 'approval',
    memberLimit: 200,
    postPermission: 'all',
    creator: {
      nickname: '面试达人',
      role: '管理员',
      joinTime: '2024-04-05 10:15:00'
    },
    membersList: [],
    activities: []
  },
  {
    groupId: 'G004',
    name: '公共基础知识加油站',
    category: '公基',
    description: '公共基础知识学习交流，知识点梳理，真题练习，助你轻松掌握公基内容。',
    avatar: 'https://picsum.photos/id/1004/200/200',
    members: 189,
    activityCount: 15,
    status: 'active',
    createTime: '2024-04-01 16:40:00',
    isPublic: true,
    joinMethod: 'open',
    memberLimit: 0,
    postPermission: 'all',
    creator: {
      nickname: '公基大师',
      role: '管理员',
      joinTime: '2024-04-01 16:40:00'
    },
    membersList: [],
    activities: []
  },
  {
    groupId: 'G005',
    name: '2024省考交流群',
    category: '其他',
    description: '2024年省考备考交流，分享考试信息、备考经验和学习资料。',
    avatar: 'https://picsum.photos/id/1005/200/200',
    members: 456,
    activityCount: 32,
    status: 'pending',
    createTime: '2024-03-28 09:25:00',
    isPublic: true,
    joinMethod: 'open',
    memberLimit: 1000,
    postPermission: 'all',
    creator: {
      nickname: '省考冲刺',
      role: '普通用户',
      joinTime: '2024-03-28 09:25:00'
    },
    membersList: [],
    activities: []
  }
]);

// 是否有选中项
const hasSelection = computed(() => {
  return selectedRows.value.length > 0;
});

// 截断内容，用于表格显示
const truncateContent = (content: string) => {
  const plainText = content.replace(/<[^>]+>/g, '');
  return plainText.length > 50 ? plainText.substring(0, 50) + '...' : content;
};

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '正常',
    pending: '审核中',
    disabled: '已禁用'
  };
  return statusMap[status] || status;
};

// 获取状态标签样式
const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    active: 'el-tag--success',
    pending: 'el-tag--warning',
    disabled: 'el-tag--danger'
  };
  return classMap[status] || '';
};

// 获取活动状态标签样式
const getActivityStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    '已完成': 'el-tag--success',
    '进行中': 'el-tag--primary',
    '即将开始': 'el-tag--warning',
    '已取消': 'el-tag--danger'
  };
  return classMap[status] || '';
};

// 搜索小组
const searchGroups = () => {
  // 模拟搜索逻辑
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    ElMessage.success('搜索完成');
  }, 500);
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadGroups();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  loadGroups();
};

// 加载小组数据
const loadGroups = () => {
  // 模拟加载数据
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    // 这里应该是实际的加载数据逻辑
  }, 500);
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 查看小组详情
const viewGroupDetail = (group: any) => {
  selectedGroup.value = { ...group };
  showGroupDetailModal.value = true;
};

// 创建小组
const createGroup = () => {
  editingGroup.value = false;
  // 重置表单
  Object.assign(groupForm, {
    groupId: '',
    name: '',
    category: '行测',
    description: '',
    avatar: '',
    isPublic: true,
    joinMethod: 'open',
    memberLimit: 0,
    postPermission: 'all'
  });
  showCreateEditModal.value = true;
};

// 编辑小组
const editGroup = (group: any) => {
  editingGroup.value = true;
  // 填充表单数据
  Object.assign(groupForm, {
    groupId: group.groupId,
    name: group.name,
    category: group.category,
    description: group.description,
    avatar: group.avatar || '',
    isPublic: group.isPublic !== undefined ? group.isPublic : true,
    joinMethod: group.joinMethod || 'open',
    memberLimit: group.memberLimit || 0,
    postPermission: group.postPermission || 'all'
  });
  showCreateEditModal.value = true;
};

// 关闭创建/编辑模态框
const closeCreateEditModal = () => {
  showCreateEditModal.value = false;
  // 重置表单验证
  if (groupForm) {
    // 这里应该重置表单验证状态
  }
};

// 保存小组
const saveGroup = () => {
  // 模拟保存小组
  isLoading.value = true;
  setTimeout(() => {
    isLoading.value = false;
    
    if (editingGroup.value) {
      // 更新现有小组
      const index = groupsData.value.findIndex(g => g.groupId === groupForm.groupId);
      if (index !== -1) {
        groupsData.value[index] = { ...groupsData.value[index], ...groupForm };
      }
      ElMessage.success('小组更新成功');
    } else {
      // 创建新小组
      const newGroup = {
        ...groupForm,
        groupId: `G${String(groupsData.value.length + 1).padStart(3, '0')}`,
        createTime: new Date().toLocaleString('zh-CN'),
        members: 1, // 创建者自己
        activityCount: 0,
        status: 'pending',
        creator: {
          nickname: '当前管理员',
          role: '管理员',
          joinTime: new Date().toLocaleString('zh-CN')
        },
        membersList: [],
        activities: []
      };
      groupsData.value.unshift(newGroup);
      ElMessage.success('小组创建成功，等待审核');
    }
    
    showCreateEditModal.value = false;
  }, 500);
};

// 切换小组状态
const toggleGroupStatus = (group: any) => {
  const newStatus = group.status === 'active' ? 'disabled' : 'active';
  const statusText = newStatus === 'active' ? '启用' : '禁用';
  
  ElMessageBox.confirm(
    `确定要${statusText}此小组吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟更新状态
    isLoading.value = true;
    setTimeout(() => {
      isLoading.value = false;
      // 更新本地数据
      const index = groupsData.value.findIndex(g => g.groupId === group.groupId);
      if (index !== -1) {
        groupsData.value[index].status = newStatus;
      }
      if (selectedGroup.value && selectedGroup.value.groupId === group.groupId) {
        selectedGroup.value.status = newStatus;
      }
      ElMessage.success(`小组${statusText}成功`);
    }, 500);
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 修改成员角色
const changeMemberRole = (_member: any) => {
  ElMessage.info('修改成员角色功能待实现');
};

// 移除成员
const removeMember = (member: any) => {
  ElMessageBox.confirm(
    `确定要移除成员"${member.nickname}"吗？`,
    '确认移除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    if (selectedGroup.value && selectedGroup.value.membersList) {
      selectedGroup.value.membersList = selectedGroup.value.membersList.filter((m: any) => m.userId !== member.userId);
      ElMessage.success('成员移除成功');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 批量操作
const batchActions = () => {
  // 触发下拉菜单显示
  const batchActionsDropdown = ref<any>(null);
  if (batchActionsDropdown.value) {
    batchActionsDropdown.value.handleClick();
  }
};

// 处理批量命令
const handleBatchCommand = (command: string) => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的小组');
    return;
  }
  
  let confirmMessage = '';
  let successMessage = '';
  let status = '';
  
  switch (command) {
    case 'batchEnable':
      confirmMessage = '确定要批量启用选中的小组吗？';
      successMessage = '小组批量启用成功';
      status = 'active';
      break;
    case 'batchDisable':
      confirmMessage = '确定要批量禁用选中的小组吗？';
      successMessage = '小组批量禁用成功';
      status = 'disabled';
      break;
    case 'batchDelete':
      confirmMessage = '确定要批量删除选中的小组吗？此操作不可撤销！';
      successMessage = '小组批量删除成功';
      break;
    default:
      return;
  }
  
  ElMessageBox.confirm(
    confirmMessage,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: command === 'batchDelete' ? 'error' : 'warning'
    }
  ).then(() => {
    // 模拟批量操作
    isLoading.value = true;
    setTimeout(() => {
      isLoading.value = false;
      
      if (command === 'batchDelete') {
        // 批量删除
        const groupIds = selectedRows.value.map(row => row.groupId);
        groupsData.value = groupsData.value.filter(g => !groupIds.includes(g.groupId));
      } else {
        // 批量启用/禁用
        selectedRows.value.forEach(row => {
          const index = groupsData.value.findIndex(g => g.groupId === row.groupId);
          if (index !== -1) {
            groupsData.value[index].status = status;
          }
        });
      }
      
      // 清空选中状态
      selectedRows.value = [];
      
      ElMessage.success(successMessage);
    }, 800);
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 导出小组列表
const exportGroupList = () => {
  // 模拟导出列表
  ElMessage.success('小组列表导出成功');
};

// 头像上传相关方法
const handleAvatarSuccess = (_res: any, file: File) => {
  // 模拟上传成功
  groupForm.avatar = URL.createObjectURL(file);
};

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  
  return isJPG && isLt2M;
};
</script>

<style lang="scss" scoped>
.admin-groups-view {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 5px 0 0 0;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.search-filters {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.status-select,
.category-select {
  width: 150px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 5px;
}

.stat-icon {
  font-size: 36px;
  color: #6366f1;
  opacity: 0.8;
}

.table-card {
  border-radius: 8px;
  overflow: hidden;
}

.group-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-avatar {
  width: 40px;
  height: 40px;
  border: 2px solid #f3f4f6;
}

.group-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.group-description {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.6;
}

.member-count {
  font-size: 14px;
  font-weight: 500;
  color: #6366f1;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.group-detail {
  padding: 20px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 20px;
}

.group-avatar-large {
  width: 100px;
  height: 100px;
  border: 3px solid #f3f4f6;
}

.group-header-info {
  flex: 1;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.group-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #6b7280;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.detail-tabs {
  margin: 20px 0;
}

.tab-content {
  padding: 20px 0;
}

.info-section {
  margin-bottom: 30px;
}

.info-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 15px;
}

.description-content {
  font-size: 14px;
  color: #4b5563;
  line-height: 1.8;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.creator-avatar {
  width: 60px;
  height: 60px;
  border: 2px solid #f3f4f6;
}

.creator-details {
  flex: 1;
}

.creator-name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin: 0 0 5px 0;
}

.creator-role {
  font-size: 14px;
  color: #6366f1;
  margin: 0 0 5px 0;
}

.creator-join-date {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.settings-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.setting-label {
  font-size: 14px;
  color: #6b7280;
}

.setting-value {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.members-table-section,
.activities-table-section {
  max-height: 500px;
  overflow-y: auto;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border: 2px solid #f3f4f6;
}

.member-details {
  flex: 1;
}

.member-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin: 0 0 5px 0;
}

.member-role {
  font-size: 12px;
  color: #6366f1;
  margin: 0;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

/* 头像上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #6366f1;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-filters {
    justify-content: flex-start;
  }
  
  .stats-cards {
    flex-wrap: wrap;
  }
  
  .stat-card {
    flex: 1 1 calc(50% - 10px);
  }
  
  .settings-list {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .search-filters {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-input,
  .status-select,
  .category-select {
    width: 100%;
  }
  
  .stat-card {
    flex: 1 1 100%;
  }
  
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .group-avatar-large {
    width: 80px;
    height: 80px;
  }
  
  .group-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>